<template>
  <!-- 安东呼叫设定表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="50%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="6">
              <el-form-item
                label="设定编号"
                style="width: 310px"
                prop="callSettingCode"
              >
                <span>{{ formData.callSettingCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="设定描述"
                style="width: 310px"
                prop="callSettingName"
              >
                <span>{{ formData.callSettingName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="公司"
                style="width: 290px"
                prop="organizationId"
              >
                <span>{{ formData.organizationCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="工厂" style="width: 310px" prop="plantId">
                <span> {{ formData.plantCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="呼叫类型"
                style="width: 310px"
                prop="plantId"
              >
                <span> {{ formData.callTypeName }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item
                label="是否启用"
                style="width: 310px"
                prop="enabled"
              >
                <span>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="创建时间"
                style="width: 310px"
                prop="createTime"
              >
                <span>{{ formData.createTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="创建人"
                style="width: 310px"
                prop="createdUserName"
              >
                <span>{{ formData.createdUserName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" style="width: 310px" prop="remarks">
                <span>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增
            </el-button>
          </template>
          <div class="formTable">
            <el-table
              :data="formData.areaDetails"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="工作中心"
                props="workCenterId"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'areaDetails.' + $index + '.workCenterId'"
                    :rules="rules.sonworkCenterId"
                    label-width="0"
                  >
                    <!-- 已经使用的ids列表  ids已经选择 -->
                    <!-- v-if="(item.id buzai 已经使用的ids列表 && item.id 不在ids已经选择) || item.id == row.workCenterId"     v-if="1 == 2"-->
                    <el-select
                      :ref="'areaDetails.' + $index + '.id'"
                      v-if="!props.isReadonly"
                      v-model="row.workCenterId"
                      placeholder="请选择工作中心"
                      filterable
                      @change="(model) => handleWorkShopData(model, $index)"
                    >
                      <el-option
                        v-for="item in row.workCenterListnow"
                        :key="item.id"
                        :label="item.workshopName"
                        :value="item.id"
                        :disabled="selectedIds.indexOf(item.id) > -1"
                      />
                    </el-select>
                    <span v-else>{{ row.workShopName }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" props="remarks" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'areaDetails.' + $index + '.remarks'"
                    :rules="rules.sonremarks"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.remarks"
                      placeholder="请输入备注"
                      clearable
                    />
                    <span v-else>{{ row.remarks }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="是否启用" props="enabled" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'areaDetails.' + $index + '.enabled'"
                    :rules="rules.sonenabled"
                    label-width="0"
                  >
                    <el-radio-group
                      v-model="row.enabled"
                      v-if="!props.isReadonly"
                    >
                      <el-radio :label="1">启用</el-radio>
                      <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                    <span v-else>{{ row.enabled == 1 ? "启用" : "停用" }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="300"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.areaDetails.length < 1"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                  >
                    <i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ANDONANDCALLAREASETTINGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
const workCenterTmpList = ref([]);
var workCenterList = ref([]);
var areaSettingNoUseList = ref([]);
var areaSettingUseList = ref([]);
var ids = ref([]);
const workCenter = reactive({
  id: "",
  workshopName: "",
  workshopCode: "",
});
let formData = reactive({
  id: "",
  callSettingId: "",
  callSettingCode: "",
  workCenterId: "",
  workCenterCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  areaDetails: [
    {
      id: "",
      callSettingId: "",
      callSettingCode: "",
      workCenterId: "",
      workCenterCode: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
      workCenterListnow: [],
    },
  ],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        callSettingId,
        callSettingCode,
        workCenterId,
        workCenterCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        callSettingId,
        callSettingCode,
        workCenterId,
        workCenterCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
    }
  }
);

/** rules规则 */
const rules = reactive({
  soncallSettingId: [
    { required: true, message: "请输入安东呼叫设定id", trigger: "blur" },
  ],
  soncallSettingCode: [
    { required: true, message: "请输入安东呼叫设定编号", trigger: "blur" },
  ],
  sonworkCenterId: [
    { required: true, message: "请输入工作中心id", trigger: "blur" },
  ],
  sonworkCenterCode: [
    { required: true, message: "请输入工作中心编号", trigger: "blur" },
  ],
  sonversion: [
    { required: true, message: "请输入数据版本号", trigger: "blur" },
  ],
  sonremarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
  soncreateTime: [
    { required: true, message: "请输入创建时间", trigger: "blur" },
  ],
  soncreatedUserId: [
    { required: true, message: "请输入创建人", trigger: "blur" },
  ],
  soncreatedUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  sonlastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  sonlastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  sonenabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  sondeleted: [{ required: true, message: "请输入删除标识", trigger: "blur" }],
});

const selectedIds = ref([]);

function handleWorkShopData(model, index) {
  selectedIds.value = [];
  formData.areaDetails.forEach((item) => {
    selectedIds.value.push(item.workCenterId);
  });
}

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.areaDetails.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  callSettingId: "",
  callSettingCode: "",
  workCenterId: "",
  workCenterCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  workCenterListnow: [],
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  sondata.callSettingId = formData.id;
  sondata.callSettingCode = formData.callSettingCode;
  formData.areaDetails.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getWorkshops();
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.callSettingId = "";
  formData.callSettingCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);
const workCenterListnow = ref([]);

async function getWorkshops() {
  workCenterListnow.value = [];
  //所有已使用
  await request({
    url: "andon/andcallareasetting/getListAllUseByPlantId",
    method: "post",
    data: {
      plantId: formData.plantId,
    },
  }).then((res) => {
    areaSettingNoUseList.value = res.data;
  });
  await request({
    url: "andon/andcallareasetting/getList",
    method: "post",
    data: {
      plantId: formData.plantId,
      id: formData.id,
    },
  }).then((res) => {
    areaSettingUseList.value = res.data;
  });

  //所有工作中心
  await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: {
      plantId: formData.plantId,
    },
  }).then((res) => {
    workCenterTmpList.value = res.data;
  });

  let sondetails = await request({
    url: "/andon/andcallareasetting/getAndcallareasettings",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.areaDetails = sondetails.data;
  selectedIds.value = [];
  formData.areaDetails.forEach((item) => {
    selectedIds.value.push(item.workCenterId);
  });

  let listIds = [];
  formData.areaDetails.forEach((detail) => {
    listIds.push(detail.workCenterId);
  });

  //从工作中心中筛选出未使用的
  workCenterList = ref([]);
  let usedIds = [];
  areaSettingUseList.value.forEach((itemdata) => {
    usedIds.push(itemdata.workCenterId);
  });

  workCenterTmpList.value.forEach((itemdata) => {
    if (
      usedIds.indexOf(itemdata.id) <= -1 ||
      listIds.indexOf(itemdata.id) > -1
    ) {
      workCenterListnow.value.push(itemdata);
    }
  });

  formData.areaDetails.forEach((detail) => {
    detail.workCenterListnow = workCenterListnow.value;
  });

  details.workCenterListnow = workCenterListnow.value;
}

/** 安东呼叫设定保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/andon/andcallareasetting/saves",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
